package com.doudou.oauth.config;

import com.doudou.oauth.config.sms.SmsCodeAuthenticationSecurityConfig;
import com.doudou.oauth.config.validate.ValidateCodeSecurityConfig;
import com.doudou.oauth.handler.FailLoginHandler;
import com.doudou.oauth.handler.SuccessLoginHandler;
import com.doudou.oauth.handler.SuccessLogoutHandler;
import com.doudou.oauth.provider.AccessTokenRemoteAuthenticationProvider;
import com.doudou.oauth.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author 傻男人
 * @date 2020-05-06 21:32
 * @describe  * 认证服务安全配置
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    ConsumerTokenServices consumerTokenServices;

    @Autowired
    private SuccessLoginHandler successLoginHandler;

    @Autowired
    private FailLoginHandler failLoginHandler;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        //配置用户来源于数据库
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
        // 认证后不清除密码信息
        auth.eraseCredentials(true);
        //设置用户密码认证处理
        auth.authenticationProvider(authenticationProvider());
        //  远程token登录
        auth.authenticationProvider(accessTokenRemoteAuthenticationProvider());
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        daoAuthenticationProvider.setUserDetailsService(userDetailsService());
        return daoAuthenticationProvider;
    }

    /**
     * 远程token登录认证
     * @return
     */
    @Bean
    AccessTokenRemoteAuthenticationProvider accessTokenRemoteAuthenticationProvider(){
        AccessTokenRemoteAuthenticationProvider accessTokenRemoteAuthenticationProvider
                = new AccessTokenRemoteAuthenticationProvider();
        accessTokenRemoteAuthenticationProvider.setTokenStore(tokenStore);
        return accessTokenRemoteAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.apply(validateCodeSecurityConfig).and().apply(smsCodeAuthenticationSecurityConfig);

        SuccessLogoutHandler successLogoutHandler =  new SuccessLogoutHandler();
        successLogoutHandler.setConsumerTokenServices(consumerTokenServices);
        //启用http 基础验证
        http.httpBasic().and()
                .authorizeRequests()
                .antMatchers("/static/**",
                        "/index.html**",
                        "/failurePage",
                        "/successLogout",
                        "/login",
                        "/index.html",
                        "/images/**",
                        "/pc_index.html**",
                        "/mobile.html**",
                        "/code/sms**",
                        "/code/**",
                        "/login.html**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .logout()
                .logoutSuccessHandler(successLogoutHandler)
                .and()
                .formLogin()
                .loginPage("/login")
                .successHandler(successLoginHandler)
                .failureHandler(failLoginHandler)
                .successForwardUrl("/successPage")
                .failureForwardUrl("/failurePage")
                .permitAll()
                .and()
                .csrf().disable();
    }

    /**
     * 需要配置这个支持password模式
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
